﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

public class ResourceMgr : MonoSingleton<ResourceMgr>
{
    private Hashtable assetTable = new Hashtable();

    /// <summary>
    /// 加载资源
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <returns></returns>
    public T LoadAsset<T>(string path) where T : UnityEngine.Object
    {
        if (assetTable.ContainsKey(path))
            return assetTable[path] as T;
        T asset = default(T);
        asset = Resources.Load<T>(path);
        if (!assetTable.ContainsKey(path))
            assetTable.Add(path, asset);
        return asset;
    }

    /// <summary>
    /// 异步加载
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="path"></param>
    /// <returns></returns>
    public IEnumerator LoadAssetAsync<T>(string path, Action<T> callBack) where T : UnityEngine.Object
    {
        T asset = default(T);
        if (assetTable.ContainsKey(path))
        {
            if(callBack != null)
                callBack((T)assetTable[path]);
            yield break;
        }

        ResourceRequest request = Resources.LoadAsync<T>(path);
        while (!request.isDone)
        {
            yield return null;
        }
        if (request.isDone)
        {
            if (!assetTable.ContainsKey(path))
                assetTable.Add(path, asset);
            if(callBack != null)
                callBack((T)request.asset);
        }
    }

    /// <summary>
    /// 加载文本资源
    /// </summary>
    /// <param name="path"></param>
    /// <returns></returns>
    public TextAsset LoadTextAsset(string path)
    {
        return LoadAsset<TextAsset>(path);
    }

    /// <summary>
    /// 异步加载资源
    /// </summary>
    /// <param name="path"></param>
    /// <param name="callBack"></param>
    /// <returns></returns>
    public void LoadObjectAsync(string path, Action<GameObject> callBack)
    {
        StartCoroutine(LoadAssetAsync(path, callBack));
    }
}
